package com.junxonline.instant.admin.service.console.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junxonline.instant.admin.service.console.ConsoleService;
import com.junxonline.instant.common.annotation.DataScope;
import com.junxonline.instant.dao.entity.dto.console.ConsoleDTO;
import com.junxonline.instant.dao.entity.model.device.Terminal;
import com.junxonline.instant.dao.entity.vo.console.ConsoleVO;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 控制台接口实现类
 *
 * @author JunX
 * @date 2021-11-12
 */
@Service
@Transactional
public class ConsoleServiceImpl implements ConsoleService {

    @Autowired
    private TerminalMapper terminalMapper;

    /**
     * 获取控制台统计数据
     *
     * @param vo      请求参数
     * @param wrapper 条件查询器
     * @return ConsoleDTO
     */
    @Override
    @DataScope(isExistCreateId = false)
    @SuppressWarnings(value = "unchecked")
    public ConsoleDTO getStatisticsData(ConsoleVO vo, QueryWrapper wrapper) {

        ConsoleDTO dto = new ConsoleDTO();

        List<Integer> terminalConnectList = new ArrayList<>();
        Set<Long> playingTerminalSet = new HashSet<>();
        Set<Long> stoppingTerminalSet = new HashSet<>();
        Set<Long> offlineTerminalSet = new HashSet<>();
        Set<Long> moreDayOfflineTerminalSet = new HashSet<>();

        // 获取所有终端数据
        QueryWrapper<Terminal> terminalQueryWrapper = (QueryWrapper<Terminal>) wrapper;
        List<Terminal> terminalList = terminalMapper.queryList(terminalQueryWrapper);

        // 以终端为单位条件去查询相关的统计数据
        for (Terminal terminal : terminalList) {
            Long id = terminal.getId();
            Integer status = terminal.getStatus();

            // 统计终端连接情况
            // 离线
            if (status.equals(0) || status.equals(3)) {
                offlineTerminalSet.add(id);
                // 多日离线
                if (status.equals(3)) {
                    moreDayOfflineTerminalSet.add(id);
                }
            }
            // 停止
            else if (status.equals(1)) {
                stoppingTerminalSet.add(id);
            }
            // 播放
            else if (status.equals(2)) {
                playingTerminalSet.add(id);
            }
        }

        // 汇总数据
        dto.setPlayingTerminalCount(playingTerminalSet.size());
        dto.setStoppingTerminalCount(stoppingTerminalSet.size());
        dto.setOfflineTerminalCount(offlineTerminalSet.size());
        dto.setMoreDayOfflineTerminalCount(moreDayOfflineTerminalSet.size());

        return dto;
    }

}
